package com.example.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.result.Result;
import com.example.entity.mes.Maintain;
import com.example.entity.mes.Sked;
import com.example.entity.mes.SkedEquipment;
import com.example.entity.mes.SkedMaintain;
import com.example.mapper.MaintainMapper;
import com.example.mapper.SkedMapper;
import com.example.service.SkedMaintainService;
import com.example.mapper.SkedMaintainMapper;
import lombok.extern.java.Log;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author 14501
* @description 针对表【sked_maintain】的数据库操作Service实现
* @createDate 2024-03-14 15:07:36
*/
@Service
@Log
public class SkedMaintainServiceImpl extends ServiceImpl<SkedMaintainMapper, SkedMaintain> implements SkedMaintainService{

    @Resource
    private SkedMaintainMapper skedMaintainMapper;
    @Resource
    private MaintainMapper maintainMapper;

    @Override
    @DS("mes")
    @Transactional(rollbackFor = Exception.class) // 批量执行需要加上事务,其中报错,进行回滚操作
    public Result insertskedMaintainBatch(List<SkedMaintain> skedMaintains) {
        try {
            List<String> list = new ArrayList<>();
            Integer integer = 0;
            for (SkedMaintain arr:skedMaintains) {
                SkedMaintain mid = this.skedMaintainMapper.selectOne(new QueryWrapper<SkedMaintain>().eq("mid", arr.getMid()));
                log.info("query SkedMaintain mid=arr.getMid { }");
                if (mid==null){
                    int insert = this.skedMaintainMapper.insert(arr);
                    if (insert>0){
                        integer++;
                    }
                }else{
                    Maintain maintain = maintainMapper.selectOne(new QueryWrapper<Maintain>().eq("id", arr.getMid()));
                    list.add(maintain.getName()+"项目已添加");
                }
            }
            if (integer!=skedMaintains.size()){
                return Result.error(list);
            }
            return Result.success("新增成功");
        }catch (Exception e){
            return Result.error("新增异常"+e);
        }
    }

    @Override
    @DS("mes")
    @Transactional(rollbackFor = Exception.class) // 批量执行需要加上事务,其中报错,进行回滚操作
    public Result deleteSkedMaintainBatch(List<Integer> idlist) {
        try{
            boolean b = this.removeByIds(idlist);
            if (b){
                return Result.success("删除成功");
            }else{
                return Result.error("删除失败","500");
            }
        }catch (Exception e){
            return Result.error("删除发生异常"+e,"500");
        }
    }
}




